package it.progettoso.thread;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.telephony.SmsManager;
import android.widget.Toast;

public class WiFiLocationThread implements Runnable{
	
	protected String mess="";
	protected double Lat=0.0D,Long=0.0D;
	
	private Context c;
	private String phone;
	private LocationManager lm;
	private LocationListener locationListener;
	private HandlerThread mthread;
	AudioManager manager=null;
	
	public WiFiLocationThread(Context context, String phone, HandlerThread mthread){
		this.phone=phone;
		this.c=context;
		this.mthread=mthread;
		lm = (LocationManager)c.getSystemService(Context.LOCATION_SERVICE); 
		locationListener = new MyLocationListener();
	}
	
	@Override
	public void run() {	
		lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,10,locationListener);		
	}

	private class MyLocationListener implements LocationListener
	{
		@Override
		public void onLocationChanged(Location loc) {
			if (loc != null) {
				Lat=loc.getLatitude();
				Long=loc.getLongitude();
				mess="Info WI-FI: Latitudine: "+loc.getLatitude() 
				+ " Longitudine: "+loc.getLongitude();
				sendSMS(phone, mess);
				mthread.getLooper().quit();
			}else{
				Toast.makeText(c,"Location NULL", Toast.LENGTH_SHORT).show();
			}
		}
		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {

		}

		@Override
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
		}
	} 
	//---sends a SMS message to another device---
	public void sendSMS(String phoneNumber, String message){      
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, null, null);               
	}  
}
